package vip.liux.backend.adapter.web;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import vip.liux.application.dots.ListResultDto;
import vip.liux.application.dots.PagedResultDto;
import vip.liux.backend.application.service.pay.PayAppService;
import vip.liux.backend.application.service.pay.PayChannelService;
import vip.liux.backend.application.service.pay.dto.app.*;
import vip.liux.backend.application.service.pay.dto.channel.PayChannelDto;
import vip.liux.contracts.shared.enums.Status;

import javax.validation.Valid;
import java.util.stream.Collectors;

import static vip.liux.backend.infrastructure.utils.ListJoinKit.backFillToMany;


@Slf4j
@RestController
@RequestMapping("/api/pay/app")
public class PayAppController {

    @Resource
    private PayAppService appService;
    @Resource
    private PayChannelService channelService;

    @PostMapping
    public Long createApp(@Valid @RequestBody PayAppCreateDto createDto) {
        return appService.createApp(createDto);
    }

    @PutMapping("/{id}")
    public void updateApp(@PathVariable Long id, @Valid @RequestBody PayAppUpdateDto updateDto) {
        appService.updateApp(id, updateDto);
    }

    @PutMapping("/{id}/{status}")
    public void updateAppStatus(@PathVariable Long id, @PathVariable Status status) {
        appService.updateAppStatus(id, status);
    }

    @DeleteMapping("/{id}")
    public Boolean deleteApp(@PathVariable("id") Long id) {
        appService.deleteApp(id);
        return true;
    }

    @GetMapping("/{id}")
    public PayAppDto getApp(@PathVariable("id") Long id) {
        return appService.getApp(id);
    }

    @GetMapping("/page")
    public PagedResultDto<PayAppPageItemDto> getAppPage(@Valid PayAppQueryDto pageDto) {
        // 得到应用分页列表
        PagedResultDto<PayAppPageItemDto> pageResult = appService.getAppPage(pageDto);
        if (CollectionUtils.isEmpty(pageResult.getItems())) {
            return pageResult;
        }

        // 得到所有的应用编号，查出所有的渠道，并移除未启用的渠道
        ListResultDto<PayChannelDto> channels = channelService.getChannelListByAppIds(
                pageResult.getItems().stream().map(PayAppPageItemDto::getId).collect(Collectors.toList()));
        channels.getItems().removeIf(channel -> !Status.ENABLED.equals(channel.getStatus()));

        backFillToMany(
                pageResult.getItems(), channels.getItems(),
                PayAppPageItemDto::getId, PayChannelDto::getAppId,
                (app, channel) -> app.getChannelCodes().addAll(channel.stream().map(PayChannelDto::getCode).toList()));

        // 拼接后返回
        return pageResult;
    }

    @GetMapping
    public ListResultDto<PayAppDto> getAppList() {
        return appService.getAppList();
    }
}
